package com.example.module_user.viewmodel

import androidx.lifecycle.viewModelScope
import com.example.lib_base.BaseViewModel
import com.example.module_user.intent.UserIntent
import com.example.module_user.model.UserModel
import com.example.module_user.state.UserState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import kotlin.math.log

class UserViewModel:BaseViewModel<UserIntent>() {
    private val model by lazy{UserModel()}
    private val mutableState= MutableStateFlow<UserState>(UserState.Loading)
    val observerState:StateFlow<UserState>
    get() = mutableState
    init {
        viewModelScope.launch {
            channel.consumeAsFlow().collect{
                when(it){
                    is UserIntent.Login->{
                        val login = model.login(it.pas, it.username)
                        if(login.code==0){
                            mutableState.value=UserState.LoginSuccess(login.data)
                        }else{
                            mutableState.value=UserState.Failure(login.msg)
                        }
                    }
                    is UserIntent.Register->{
                        val register = model.register(it.pas, it.username)
                        if(register.code==0){
                            mutableState.value=UserState.RegisterSuccess(register.data)
                        }else{
                            mutableState.value=UserState.Failure(register.msg)
                        }
                    }
                }
            }
        }
    }
}